package cn.xiaopengstack.domain.trade.rule.settlement;

import cn.xiaopengstack.domain.trade.rule.factory.SettlementRuleFilterFactory;
import cn.xiaopengstack.domain.trade.model.entity.GroupBuyOrderEntity;
import cn.xiaopengstack.domain.trade.model.entity.MarketOrderEntity;
import cn.xiaopengstack.domain.trade.model.entity.SettlementRuleCommandEntity;
import cn.xiaopengstack.domain.trade.model.entity.SettlementRuleResponseEntity;
import cn.xiaopengstack.domain.trade.repository.ITradeRepository;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author jiangyangang
 */
@Component
@Slf4j
public class SettlementValidateFilter extends AbstractSettlementLogicLink<SettlementRuleCommandEntity, SettlementRuleFilterFactory.DynamicContext, SettlementRuleResponseEntity> {

    public SettlementValidateFilter(ITradeRepository tradeRepository) {
        super(tradeRepository);
    }

    @Override
    public SettlementRuleResponseEntity apply(SettlementRuleCommandEntity request, SettlementRuleFilterFactory.DynamicContext dynamic) throws Exception {
        log.info("结算规则流。结算订单有效性校验节点开始");
        MarketOrderEntity marketOrderEntity = dynamic.getMarketOrderEntity();
        GroupBuyOrderEntity groupBuyOrderEntity = tradeRepository.queryOrderByTeamId(marketOrderEntity.getTeamId()).orElseThrow(() -> new AppException(ResponseCode.SETTLEMENT_FILTER_EMPTY_TEAM_FAIL.getCode(), ResponseCode.SETTLEMENT_FILTER_EMPTY_TEAM_FAIL.getInfo()));
        Date nowTime = new Date();
        if (groupBuyOrderEntity.getGroupStartTime().after(nowTime) || groupBuyOrderEntity.getGroupEndTime().before(nowTime)){
            throw new AppException(ResponseCode.SETTLEMENT_FILTER_GROUP_TIME_EXPIRED.getCode(), ResponseCode.SETTLEMENT_FILTER_GROUP_TIME_EXPIRED.getInfo());
        }

        dynamic.setGroupBuyOrderEntity(groupBuyOrderEntity);

        return next(request, dynamic);
    }

}
